<?php
namespace Cashier;

class Notifier
{
    public function post($uri, $param)
    {

    }

    /**
     * 用get请求方式发送支付完成
     */
    public function get($url = '', $param = array(), $key = '')
    {
        if (empty($url) or !is_array($param) or empty($key)) {
            throw new \Exception('系统出错, 参数不足', 500);
        }

        // 拼Sign
        $signLib = new Sign();
        $signParams = $signLib->paraFilter($param);
        $signParams = $signLib->argSort($signParams);
        $linkString = $signLib->createLinkstring($signParams);

        // TODO 如果是MD5加密方式, 如果是其他? 通知暂时都用MD5吧
        $param['sign'] = $signLib->md5Sign($linkString, $key);
        $param['signtype'] = 'MD5';

        // 发送请求
        $raw = $this->_getRequest($url, $param);

        /* 整理结果 return成功失败
        if (!empty($httpInfo) and 'success' == $httpInfo) {
            return true;
        }
        //*/

        // 整理结果 return成功失败
        if (!empty($raw)
            and $json = json_decode($raw, true)
            and isset($json['status'])
            and ('200' == $json['status'] or 'success' == $json['status'])) {
            return true;
        }

        $msg = isset($json['msg']) ? $json['msg'] : '没msg';
        $code = isset($json['status']) ? (int)$json['status'] : '0';
        throw new \Exception('不成功, 内容为:' . $msg, $code);
    }

    /**
     * 发送HTTP请求
     */
    private function _getRequest($url, $data, $timeout = 6)
    {
        if (is_string($data)) {
            $real_url = $url . (strpos($url, '?') === false ? '?' : '') . $data;
        } else {
            $real_url = $url . (strpos($url, '?') === false ? '?' : '') . http_build_query($data);
        }

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $real_url);
        // curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); // 不follow他们的redirect
        // curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_FORBID_REUSE, 1);
        curl_setopt($ch, CURLOPT_FRESH_CONNECT, 1);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);

        $ret = curl_exec($ch);
        $info = curl_getinfo($ch);
        curl_close($ch);

        if (200 != $info['http_code']) {
            throw new \Exception('通知后对方返回非200头: ' . json_encode($info), 400);
        }

        return $ret;
    }
}


// end Cashier